#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "pcb.h"
#include "tracereader.h"

/* global */
int debug;

FILE* trace_f;
int done = 0;

char* CommandName;
unsigned StartTime;
double CPUTime = 0.0;
unsigned pid;
unsigned IOCount;

unsigned timeline_size;
unsigned* io_timeline;

static int readLine();

void openTrace(char* filename)
{
	trace_f = fopen(filename, "r");

	if(NULL==trace_f){
		fprintf(stderr, "Unable to open %s\n", filename);
        exit(EXIT_FAILURE);
    } 

	if(readLine()){
		fprintf(stderr, "Empty file?\n");
		exit(EXIT_FAILURE);
	}
}

int isTraceComplete(){
	return done;
}

unsigned nextProcessStartTime()
{
	return StartTime;
	 
}

PCB* getNextProcess()
{
	PCB* pcb;

	if(done){
		return NULL;
	}

	pid++;
	
	pcb = createPCB(CommandName,StartTime,CPUTime,IOCount,pid);
	
	if(debug) printStartPCB(pcb);
	
	/* read next line */
	if(readLine()){
		done = 1;
	}

	return pcb;
}

static int readLine()
{
	int rt = 0;

	CommandName = (char*) malloc(sizeof(char) * MAXCMDNAMELEN);
	if(NULL == CommandName){
		fprintf(stderr, "Failed to malloc string for cmd name.\n");
		exit(EXIT_FAILURE);
	}

	if(fscanf(trace_f, "%s %u %lf %u", CommandName, &StartTime, &CPUTime, &IOCount ) == EOF){
		rt = 1;
	}

	return rt;
}


